/**
 * 
 */
package com.edocbase.desktop.maildriver;

import java.util.Date;

import javax.mail.Message;

import com.edocbase.biz.diary.entities.MailEntity;
import com.edocbase.desktop.IPropertyConfig;
import com.edocbase.entity.EntityManager;
import com.edocbase.entity.EntityManagerFactory;
import com.edocbase.entity.StoreException;
import com.edocbase.webdriver.mail.IMailDriverStore;
import com.edocbase.webdriver.mail.MailDriver;

/**
 * @author X61
 *
 */
public class MailDriverStore implements IMailDriverStore {
	private MailDriver driver = null;
	private IPropertyConfig config;
	private EntityManager<MailEntity> mailManager = null;
	public MailDriverStore(MailDriver driver) {
		super();
		this.driver = driver;
		config = DesktopApplication.getPropertyConfig();
		mailManager = EntityManagerFactory.getEntityManager(MailEntity.class);
	}

	public MailDriver getDriver() {
		return driver;
	}

	public void setDriver(MailDriver driver) {
		this.driver = driver;
	}
	
	/* (non-Javadoc)
	 * @see com.edocbase.webdriver.mail.IMailDriverStore#hasUID(java.lang.String)
	 */
	public boolean hasUID(String uid){
		boolean has = false;
		String id = driver.getAccount().concat(",").concat(uid);
		//has = msgDao.contains(id);
		try {
			MailEntity mailMsg = mailManager.get(id);
			has = mailMsg != null;
		} catch (StoreException e) {
			e.printStackTrace();
		}
		return has;
	}

	@Override
	public void save(String subject, String mailType, String uid,Message msg) {
		int msgNo = msg.getMessageNumber();
		System.out.println("save msg " + msgNo);
		MailEntity mailMsg = new MailEntity(driver.getAccount(), uid);
		mailMsg.setReceiveDate(new Date());
		mailMsg.setSubject(subject);
		mailMsg.setType(mailType);
		mailMsg.setMessageNumber(msgNo);
		//msgDao.add(mailMsg);
		try {
			if (hasUID(uid)){
				mailManager.update(mailMsg.getId(), mailMsg);
			}else{
				mailManager.insert(mailMsg);
			}
		} catch (StoreException e) {
			e.printStackTrace(System.err);
		}
	}

	public String getString(String key, String defaultValue) {
		key ="driver." +driver.getAccount().concat(".").concat(key);
		return config.getString(key, defaultValue);
	}

	public void setProperty(String key, Object value) {
		key = "driver." +driver.getAccount().concat(".").concat(key);
		
		config.setProperty(key, value);
	}

	@Override
	public void close() {
		
	}
	
}
